package authentication;

import br.com.caelum.vraptor.ioc.Component;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

//@SessionScoped
@Component
public class ShiroMembershipProvider implements IMembershipProvider {

    //private static final Logger logger = LoggerFactory.getLogger(ShiroMembershipProvider.class);

    private Subject currentUser;
    public ShiroMembershipProvider() {
        //currentUser = SecurityUtils.getSubject();
    }

    protected Subject getCurrentUser(){
        if(currentUser == null){
            currentUser = SecurityUtils.getSubject();
        }

        return currentUser;
    }

    @Override
    public boolean isAuthenticated(){
        return getCurrentUser().isAuthenticated();
    }

    @Override
    public String userName(){
        if(!isAuthenticated()){
            return null;
        }

        return getCurrentUser().getPrincipal().toString();
    }

    @Override
    public boolean login(String username, String password){
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            getCurrentUser().login(token);
            return true;
        }catch(AuthenticationException ex){
            return false;
        }
    }

    @Override
    public void logout(){
        getCurrentUser().logout();
    }

    @Override
    public boolean inRole(String... roles){
        try{
            boolean[] result = getCurrentUser().hasRoles(Arrays.asList(roles));
            for (boolean r : result){
                if(r){
                    return true;
                }
            }
            return false;
        }catch(AuthenticationException ex){
            return false;
        }
    }
}
